package com.live.minclient;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class CompatibleHttpHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        try {

            // 创建HTTP连接
            HttpURLConnection conn = createConnection(exchange);

            // 处理响应
            sendResponse(exchange, conn);
        } catch (Exception e) {
            e.printStackTrace();
            exchange.getResponseHeaders().add("content-type", "text/plain");
            sendError(exchange, e);
        } finally {
            exchange.close();
        }
    }

    private HttpURLConnection createConnection(HttpExchange exchange)
            throws IOException {

        InputStream inputStream = exchange.getRequestBody();
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);

        // 从请求体中获取前端发送的参数
        String requestBody = new String(bytes, StandardCharsets.UTF_8);
        JSONObject requestData = new JSONObject(requestBody);

        // 获取实际请求参数
        String actualUrl = requestData.getString("url");
        String actualMethod = requestData.getString("method");
        JSONObject headers = requestData.getJSONObject("headers");
        String body = requestData.optString("body", null);

        HttpURLConnection conn = (HttpURLConnection) new URL(actualUrl).openConnection();
        conn.setRequestMethod(actualMethod);

        // 设置请求头
        headers.keys().forEachRemaining(key -> {
            conn.setRequestProperty(key, headers.getString(key));
        });

        // 处理请求体
        if (body != null && !body.trim().isEmpty()) {
            conn.setDoOutput(true);
            try (OutputStream os = conn.getOutputStream()) {
                os.write(body.getBytes(StandardCharsets.UTF_8));
            }
        }

        return conn;
    }


    private void sendResponse(HttpExchange exchange, HttpURLConnection conn) throws IOException {
        // 设置响应头
        conn.getHeaderFields().entrySet().forEach(entry -> {
            if (entry.getKey() != null) {
                exchange.getResponseHeaders().add(entry.getKey(), entry.getValue().get(0));
            }
        });

        // 发送响应
        exchange.sendResponseHeaders(conn.getResponseCode(), 0);
        try (OutputStream os = exchange.getResponseBody();
             InputStream is = conn.getResponseCode() >= 400 ?
                     conn.getErrorStream() : conn.getInputStream()) {
            copyStream(is, os);
        }
    }

    private void sendError(HttpExchange exchange, Exception e) throws IOException {
        String response = e.getMessage();
        exchange.sendResponseHeaders(500, response.length());
        exchange.getResponseBody().write(response.getBytes());
    }

    private void copyStream(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    }

    private Map<String, String> parseQuery(String query) {
        Map<String, String> result = new HashMap<>();
        if (query == null || query.isEmpty()) return result;

        for (String param : query.split("&")) {
            int idx = param.indexOf("=");
            String key = idx > 0 ? param.substring(0, idx) : param;
            String value = idx > 0 && param.length() > idx + 1 ? param.substring(idx + 1) : "";
            result.put(key, value);
        }
        return result;
    }
}